<template>
  <div>
    <el-upload class="upload-demo" drag :auto-upload="false" action="" :on-change="handleUpload" accept=".png,.jpg,.jpeg,.svg"
      multiple :limit="20" ref="uploadRef">
      <el-icon class="el-icon--upload">
        <upload-filled />
      </el-icon>
      <div class="el-upload__text">
        将文件拖拽至此 或 <em>点击上传</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          注意：图片大小限制最大5M，超过2M时开启压缩，推荐到 <a href="https://tinypng.com/" target="_blank">"这里"</a> 压缩后上传
        </div>
      </template>
    </el-upload>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { UploadProps, UploadInstance } from 'element-plus'
import FSMessage from '@/utils/message'
import { upload, uploadBatch } from '@/api/usualManage'
import { getSuffix, compressImage } from '@/utils/tools'

const uploadRef = ref<UploadInstance>()
const formData = ref<FormData>()
formData.value = new FormData()

const handleUpload: UploadProps['onChange'] = async (
  uploadFile,
  uploadFiles
) => {
  try {
    const suffix = getSuffix(uploadFile.name)
    if (!['jpg', 'png', 'jpeg', 'svg'].includes(suffix)) {
      FSMessage.error('请上传图片(png,jpg,jpeg)格式')
      uploadRef.value.clearFiles()
      return Promise.reject('file type error')
    }
    if (uploadFile.size >= 5 * 1024 * 1024) {
      FSMessage.error(`图片:${uploadFile.name}过大，请压缩后上传`)
      uploadRef.value.clearFiles()
      return Promise.reject('file type error')
    }
    // 压缩图片(大于8MB，即开始压缩)
    if (uploadFile.size && uploadFile.size >= 2 * 1024 * 1024) {
      const res = await compressImage(uploadFile.raw)
      formData.value.append('file', res.file)
      formData.value.append('type', '1')
    } else {
      formData.value.append('file', uploadFile.raw)
      formData.value.append('type', '1')
    }
  } catch (e) {
    throw new Error(e)
  }
}

/**
 * @breif: 根据上传文件的个数自动判断使用什么接口（目的是为了保留之前的单文件上传接口，避免出错误）
 * @param {*} params
 * @return {*}
 */
const uploadFile = async (params): Promise<any> => {
  try {
    const len = formData.value.getAll('file').length
    if (len > 1) {
      const res = await uploadBatch(formData.value, params)
      return Promise.resolve(res.data)
    } else {
      const res = await upload(formData.value, params)
      return Promise.resolve(res.data)
    }
  } catch (e) {
    return Promise.reject(e)
  }
}

defineExpose({
  uploadFile
})
</script>

<style></style>
